package cn.edu.uestc.framework.exceptionhandler;

import cn.edu.uestc.framework.ajax.AjaxResponse;
import cn.edu.uestc.framework.exception.TKBusinessException;
import cn.edu.uestc.framework.exception.TKBusinessExceptionMap;
import com.google.gson.Gson;
import org.apache.log4j.Logger;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 自定义的异常处理器
 * Created by Eric on 2017/6/12.
 */
public class TKExceptionHandler implements HandlerExceptionResolver {
    private static Logger logger = Logger.getLogger(TKExceptionHandler.class);
    @Resource
    private Gson gson;

    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        AjaxResponse response;
        if (e.getClass() == TKBusinessException.class) {
            TKBusinessException tkExce = (TKBusinessException) e;

            if (tkExce.getMessage() == null) {
                response = AjaxResponse.getBusinessErrorResponse(tkExce.getErrorId(), TKBusinessExceptionMap.getInfo(tkExce.getErrorId()));
            } else {
                response = AjaxResponse.getBusinessErrorResponse(tkExce.getErrorId(), tkExce.getMessage());
            }

            String ip = httpServletRequest.getRemoteAddr();
            String requestURL = httpServletRequest.getRequestURL().toString();
            Date requestTimestamp = new Date();
            String uid = (String) httpServletRequest.getSession().getAttribute("uid");
            int errorId = tkExce.getErrorId();
            logger.error(ip + requestURL + requestTimestamp + uid + errorId);
        } else {
            response = AjaxResponse.getServerErrorResponse();
            logger.error("[Server Error] : " + e.getMessage(), e);
        }

        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try {
            httpServletResponse.getWriter().write(gson.toJson(response));
        } catch (IOException e1) {
            logger.error("无法将数据写入response", e1);
        }
        return new ModelAndView();
    }
}
